//
//  NewOrderListViewController.swift
//  OnceNectar
//
//  Created by 吴凌 on 2018/7/30.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import MJRefresh
import Networking
import Alamofire
import PKHUD
import SwiftyJSON
enum MineOrderContentType: NSInteger {
    case comment = 0
    case zan
}
class NewOrderListViewController: BaseViewController, ImageFactory,WCLWaterFallLayoutDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, AddCornerUIRectCorner, BottomShadow, UICollectionViewDelegate, UICollectionViewDataSource,OrderListFootViewDelegate {
    @IBOutlet weak var cornerSelectionView: CornerSelectionView!
    
    @IBOutlet weak var scView: UIView!
    @IBOutlet weak var orderView: UIView!
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var statusBtn: UIButton!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var collectionView: UICollectionView!
    
    private var commodityModels1: [GoodsSCModel] = []
    private var orderModels: [myOrderModel] = []
    private let itemTopBottomMargin: CGFloat =  10
    private let itemOffset: CGFloat = 10
    private var itemSize: CGSize {
        let LRMargin: CGFloat = 20
        let width = (ScreenWidth - LRMargin * 2 - itemOffset) / 2
        let height: CGFloat = 260
        return CGSize(width: width, height: height)
        
    }
    
    var page:Int = 0
    var totalPage:Int = 0
    var keyword :String = ""
    var status :String = ""
    var mineContentType: MineOrderContentType = .comment
    
    var page1:Int = 0
    var totalPage1:Int = 0
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    // 顶部刷新
    let header1 = MJRefreshNormalHeader()
    // 底部刷新
    let footer1 = MJRefreshAutoNormalFooter()
    
    /// 析构函数.类似于OC的 dealloc
    deinit {
        /// 移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let notificationName = "reloadTable"
        /// 自定义通知
        NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name: NSNotification.Name(rawValue: notificationName), object: nil)
        setUI()
    }
    
    /// 接受到通知后的方法回调
    @objc private func notificationAction(noti: Notification) {
        headerRefresh()
    }
    
    func setUI() {
        titleLabel(text: "我的订单", nil)
        tableView.register(UINib(nibName: "\(OrderListTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        tableView.register(UINib(nibName: "\(OrderListHeaderView.self)", bundle: nil), forHeaderFooterViewReuseIdentifier: "orderHeader")
        tableView.register(UINib(nibName: "\(OrderListFootView.self)", bundle: nil), forHeaderFooterViewReuseIdentifier: "orderFooter")
        tableView.bounces = true
        addCornerWithView(aView: orderView, aCorners: .allCorners, aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        addCornerWithView(aView: scView, aCorners: .allCorners, aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        setSearchBar()
        
        
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        tableView.mj_header = header
        tableView.mj_footer = footer
        
        collectionView.register(UINib(nibName: "\(MyOrderSCCell.self)", bundle: nil), forCellWithReuseIdentifier: "myOrderSCCell")
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = itemSize
        layout.minimumLineSpacing = itemTopBottomMargin
        layout.minimumLineSpacing = itemOffset
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsetsMake(itemTopBottomMargin, itemOffset, itemTopBottomMargin, itemOffset)
        collectionView.collectionViewLayout = layout
        
        collectionView.clipsToBounds = true
        
        let headerAction1:Selector = #selector(headerRefresh1)
        header1.setRefreshingTarget(self, refreshingAction: headerAction1)
        
        let footerAction1:Selector = #selector(footerRefresh1)
        footer1.setRefreshingTarget(self, refreshingAction: footerAction1)
        collectionView.mj_header = header1
        collectionView.mj_footer = footer1
        
        self.headerRefresh()
        self.headerRefresh1()
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        page = 0
        self.footerRefresh()
    }
    // 底部刷新
    @objc func footerRefresh(){
        page += 1
        self.fetchBannerList(parameters: ["page":page,"pageSize":10,"objType":"0","keyword":keyword,"status":status])
    }
    
    // 顶部刷新
    @objc func headerRefresh1(){
        page1 = 0
        self.footerRefresh1()
    }
    // 底部刷新
    @objc func footerRefresh1(){
        page1 += 1
        self.fetchProductList(parameters: ["page":page1,"pageSize":10,"objType":3])
    }
    
    override func setNavigation() {
    }
    
    override func returnVC() {
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    func setSearchBar() {
        cornerSelectionView.show(titles: ["订单", "收藏"]) {[unowned self] (index) in
            var corner: UIRectCorner!
            switch index {
            case 0:
                self.orderView.isHidden = false
                self.scView.isHidden = true
                corner = [.topRight,.bottomLeft, .bottomRight]
            case 2:
                corner = [.topLeft, .bottomLeft, .bottomRight]
            default:
                self.scView.isHidden = false
                self.orderView.isHidden = true
                corner = .allCorners
            }
            self.mineContentType = MineOrderContentType(rawValue: index)!
        }
        
        searchBar.barStyle = .blackTranslucent
        let searchImage = createImage(color: UIColor(hex: 0xBFBFBF), height: 28)
        searchBar.backgroundImage = searchImage
        
        searchBar.backgroundColor = UIColor.clear
        searchBar.setSearchFieldBackgroundImage(searchImage, for: .normal)
        searchBar.layer.cornerRadius = CORNERRADIUS
        searchBar.layer.masksToBounds = true
        let searchField = searchBar.value(forKey: "searchField") as? UITextField
        if let textField = searchField {
            textField.layer.cornerRadius = CORNERRADIUS
            textField.layer.masksToBounds = true
            textField.backgroundColor = UIColor.white
            textField.attributedPlaceholder = NSAttributedString(string: "订单编号/收件人名称/收件人电话", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 13),NSAttributedStringKey.strokeColor: UIColor.white])
            textField.textColor = UIColor.white
            textField.font = UIFont.systemFont(ofSize: 10)
            let imageView = UIImageView(image: UIImage(named: "icon_search"))
            imageView.sizeToFit()
            //            textField.delegate = self
            textField.leftView = imageView
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return orderModels.count
    }
    // MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let order = orderModels[section]
        if let count = order.purchaseGoodsInfos?.count{
            return count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 52
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let model:myOrderModel = self.orderModels[section]
        let headView :OrderListHeaderView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "orderHeader") as! OrderListHeaderView
        headView.orderNo.text = "订单编号：" + model.orderNumber!
        headView.status.text = model.statusName
        return headView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let model:myOrderModel = self.orderModels[section]
        let footView :OrderListFootView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "orderFooter") as! OrderListFootView
        footView.delegate = self
        footView.model = model
        footView.num.text = "共" + model.totalCount! + "件 ¥" + model.actualPayAmount!
        footView.amount.text = "运费:¥" + model.carriage!
        if Int(model.status!) == 0 {
            footView.btn1.isHidden = true
            footView.btn2.setTitle(" 立即支付 ", for: UIControlState.normal)
            footView.btn2.setTitleColor(ONColor.currencyRedColor, for: UIControlState.normal)
            footView.btn2.layer.borderColor = ONColor.currencyRedColor.cgColor
        } else if Int(model.status!) == 1 {
            footView.btn1.isHidden = true
            footView.btn2.setTitle("  催单  ", for: UIControlState.normal)
            footView.btn2.setTitleColor(ONColor.currencyRedColor, for: UIControlState.normal)
            footView.btn2.layer.borderColor = ONColor.currencyRedColor.cgColor
        } else if Int(model.status!) == 2 {
            footView.btn1.isHidden = false
            footView.btn1.setTitle(" 查看物流 ", for: UIControlState.normal)
            footView.btn2.setTitle(" 确认收货 ", for: UIControlState.normal)
            footView.btn2.setTitleColor(ONColor.currencyRedColor, for: UIControlState.normal)
            footView.btn2.layer.borderColor = ONColor.currencyRedColor.cgColor
        } else if Int(model.status!)! >= 3 {
            footView.btn1.isHidden = false
            footView.btn1.setTitle(" 删除订单 ", for: UIControlState.normal)
            footView.btn2.setTitle(" 再次购买 ", for: UIControlState.normal)
            footView.btn2.setTitleColor(UIColor(hex: 0xAAAAAA), for: UIControlState.normal)
            footView.btn2.layer.borderColor = UIColor(hex: 0xAAAAAA).cgColor
        } else if Int(model.status!) == -1 {
            footView.btn1.isHidden = true
            footView.btn2.setTitle(" 再次购买 ", for: UIControlState.normal)
            footView.btn2.setTitleColor(UIColor(hex: 0xAAAAAA), for: UIControlState.normal)
            footView.btn2.layer.borderColor = UIColor(hex: 0xAAAAAA).cgColor
        }
        return footView
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? OrderListTableViewCell
        cell?.backgroundColor = UIColor.white
        let model = orderModels[indexPath.section].purchaseGoodsInfos![indexPath.row]
        cell?.name.text = model.goodsName
        cell?.spec.text = model.specAndCol
        cell?.num.text = " * " + model.number!
        cell?.amount.text = "¥" + model.price!
        cell?.img.sd_setImage(with: appendUrl(suffix: model.imageUrl!), completed: nil)
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = self.orderModels[indexPath.section]
        let myDetailOrderVC = NewOrderInfoViewController(nibName: "\(NewOrderInfoViewController.self)", bundle: nil)
        myDetailOrderVC.model = model
        self.navigationController?.pushViewController(myDetailOrderVC, animated: true)
    }
    
    // MARK: - collectionViewDataSource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return commodityModels1.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let shoppingDetailVC = ShoppingDetailViewController(nibName: "\(ShoppingDetailViewController.self)", bundle: nil)
        let temp = commodityModels1[indexPath.row]
        var model = GoodsModel()
        model.id = temp.id
        model.coverPath = temp.image
        model.type = temp.redirectType
        model.shareUrl = temp.share
        model.collected = temp.collected
        shoppingDetailVC.commodityModel = model
        self.navigationController?.pushViewController(shoppingDetailVC, animated: true)
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myOrderSCCell", for: indexPath) as? MyOrderSCCell
        cell?.setData(model: commodityModels1[indexPath.row])
        return cell!
    }
    
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForItemAt indexPath: IndexPath) -> CGFloat {
        return 250
    }
    
    func columnOfWaterFall(_ collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForHeaderAt indexPath: IndexPath) -> CGFloat {
        return 0
    }
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForFooterAt indexPath: IndexPath) -> CGFloat {
        return 0
    }
    
    /// 获取商品数据
    func fetchProductList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(myShoucangUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage1 = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        if self.page1 == 1{
                                            self.commodityModels1.removeAll()
                                            self.collectionView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.collectionView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            let model = GoodsSCModel(fromDic: dic)
                                            self.commodityModels1.append(model)
                                        }
                                        if self.totalPage1 == self.commodityModels1.count{
                                            self.collectionView.mj_footer.isHidden = true
                                        }
                                        else{
                                            self.collectionView.mj_footer.isHidden = false
                                        }
                                        
                                        self.collectionView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page1 == 1{
                                            self.collectionView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.collectionView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page1 == 1{
                                    self.collectionView.mj_header.endRefreshing()
                                }
                                else{
                                    self.collectionView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
    /// 获取banner数据
    func fetchBannerList(parameters: [String: Any]) -> Void {
        var param = Dictionary<String, Any>()
        for (key, value) in parameters {
            if String.init(describing: value) != "" {
                param[key] = value
            }
        }
        let requesturl = "\(BaseURL)\(myOrderListUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: param,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        if self.page == 1{
                                            self.orderModels.removeAll()
                                            self.tableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.tableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            var model = myOrderModel(fromDic: dic)
                                            model.initLabels(arr: (dic["purchaseGoodsInfos"]?.array!)!)
                                            
                                            self.orderModels.append(model)
                                        }
                                        
                                        if self.totalPage == self.orderModels.count{
                                            self.tableView.mj_footer = nil
                                        }
                                        else{
                                            self.tableView.mj_footer = self.footer
                                        }
                                        self.tableView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.tableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.tableView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                if self.page == 1{
                                    self.tableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.tableView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        self.keyword = searchBar.text!
        self.fetchBannerList(parameters: ["page":1,"pageSize":10,"objType":"0","keyword":self.keyword,"status":status])
    }
    func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            searchBar.resignFirstResponder()
            return false
        }
        return true
    }
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        
    }
    
    @IBAction func statusQuery(_ sender: Any) {
        let imageSize = UIImage(named: "right_copy_page")
        guard let trueImageSize = imageSize else {return}
        var data: [SearchRecommendModel] = []
        let datas = ["全部", "待付款", "待出库", "已出库", "已完成", "已取消", "申请售后"]
        for subject in datas {
            var se = SearchRecommendModel()
            se.title = subject
            data.append(se)
        }
        if data.count > 0{
            RelevantRecommendationsView().showData(datas: data, rightMargin: trueImageSize.size.width * trueImageSize.scale - 50){(index) in
                if index == 0 {
                    self.status = ""
                    self.fetchBannerList(parameters: ["page":1,"pageSize":10,"objType":"0","keyword":self.keyword,"status":self.status])
                }else{
                    let idxStr = "\(index! - 1)"
                    self.status = idxStr
                    self.fetchBannerList(parameters: ["page":1,"pageSize":10,"objType":"0","keyword":self.keyword,"status":self.status])
                }
                self.statusBtn.setTitle(data[index!].title, for: UIControlState.normal)
            }
        }
        else{
            self.showToast(msg:"没有数据")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func btn1Click(model:myOrderModel) {
        if Int(model.status!) == 2 {
            pushLogistics(url: model.traceUrl!)
        } else if Int(model.status!)! >= 3 {
            let alertController = UIAlertController(title: "删除订单？", message: nil, preferredStyle: .alert)
            
            let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: { (_) in
                
            })
            let sureAction = UIAlertAction.init(title: "确定", style: .default, handler: { (_) in
                self.deleteOrder(paramaters: ["id": model.id!])
            })
            alertController.addAction(cancel)
            alertController.addAction(sureAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    func btn2Click(model:myOrderModel) {
        if Int(model.status!) == 0 {
            let payVC = PayViewController(nibName: "PayViewController", bundle: nil)
            payVC.titleLabel(text: "选择支付方式", nil)
            payVC.orderId = model.orderNumber
            self.navigationController?.pushViewController(payVC, animated: true)
        } else if Int(model.status!) == 1 {
            self.fetchreminder(parameters: ["id":(model.id)!])
        } else if Int(model.status!) == 2 {
            self.fetchConfirmReceived(parameters: ["id":(model.id)!])
        } else {
            let buyNowVC = BuyNowViewController(nibName: "\(BuyNowViewController.self)", bundle: nil)
            buyNowVC.type = 3
            buyNowVC.orderNumber = model.orderNumber
            self.navigationController?.pushViewController(buyNowVC, animated: true)
        }
    }
    
    func pushLogistics(url:String) -> Void {
        let vc:LogisticsDetailsViewController = LogisticsDetailsViewController(nibName: "\(LogisticsDetailsViewController.self)", bundle: nil)
        vc.urlPath = url
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func deleteOrder(paramaters: [String: String]) -> Void {
        let requesturl = appendUrl(suffix: deleteOrderUrl)
        Alamofire.request(requesturl, method: .get,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:json["message"].string!)
                                        self.headerRefresh()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                self.showToast(msg:"网络错误")
                            }
                            
        }
    }
    
    func cancelOrder(paramaters: [String: String]) -> Void {
        let requesturl = appendUrl(suffix: cancelOrderUrl)
        Alamofire.request(requesturl, method: .post,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:json["message"].string!)
                                        self.headerRefresh()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                self.showToast(msg:"网络错误")
                            }
                            
        }
    }
    
    /// 催单
    func fetchreminder(parameters: [String: String]) -> Void {
        let requesturl = "\(BaseURL)\(reminder)"
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:json["message"].string!)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 确认收货
    func fetchConfirmReceived(parameters: [String: String]) -> Void {
        let requesturl = "\(BaseURL)\(confirmReceived)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:json["message"].string!)
                                        self.headerRefresh()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }

}
